# coding: utf-8

import cv2
import numpy
import socket
import struct

# 建立套接字
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定树莓派IP，用户任意定制端口
#s.bind(("192.168.100.102", 6000))
s.bind(("127.0.0.1", 6000))
print("UDP bound on port 6000...")
print('now starting to send frames...')
# opencv创建视频抓取对象
capture = cv2.VideoCapture(0)
# 阻塞等待客户端访问请求
data, addr = s.recvfrom(1024)
# 设置分辨率
capture.set(3, 256)
capture.set(4, 256)

# 主循环
while True:
    # 以下三行尝试读取视频流（帧）
    success, frame = capture.read()
    while not success and frame is None:
        success, frame = capture.read()  # 获取视频帧

    # opencv对获得到的视频编码
    result, imgencode = cv2.imencode('.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, 50])
    # 发送数据（视频）大小
    s.sendto(struct.pack('i', imgencode.shape[0]), addr)
    # 发送数据
    s.sendto(imgencode, addr)
s.close()
